<template>
  <div>
    <!--<Row style="margin-bottom:10px">
        	<Col span="3">
        		<Button type="primary" class="md-add-jh" @click="fileModal.show = true"></Button>
        	</Col>
    	</Row>-->
    <div>
      <Upload
        ref="upload"
        :action="uploadAction"
        :show-upload-list="false"
        :on-format-error="handleFormatError"
        :format="['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf', 'zip', 'rar']"
        :on-success="saveCtfFiles"
        :on-progress="getProgress"
        :headers="uploadHeader"
        :before-upload="handleUpload"
        footer-hide
        style="margin-bottom: 10px; display: inline-block"
      >
	  <!-- :max-size="20480"
        :on-exceeded-size="handleUploadSize" -->
        <Button
          icon="ios-cloud-upload-outline"
          :disabled="uploadList[0] && uploadList[0].status != 'finished'"
          >{{ title ? title : "上传题目附件" }}</Button
        >
      </Upload>
      <Tooltip
        style="margin-left: 10px"
        :transfer="true"
        max-width="200"
        content="请上传doc,pdf,jpg,png,zip,rar等格式文件"
        placement="top"
      >
        <Icon type="ios-alert" class="ios-alert" />
      </Tooltip>
	  <!-- ,文件大小不能超过20M" -->
    </div>
    <div class="demo-upload-list" v-for="item in uploadList">
      <!--{{item}}-->
      <template v-if="item.status === 'finished'"> </template>
      <template v-else>
        <span style="margin-right: 5px">文件名：{{ item.name }}</span>
        <span style="margin-right: 5px"
          >文件大小：{{ getFileSize(item.size) }}</span
        >
        <span style="margin-right: 5px">上传速度：{{ speed }}</span>
        <Progress
          v-if="item.showProgress"
          :percent="item.percentage"
          hide-info
        ></Progress>
      </template>
    </div>
    <div class="chose-wrap" v-show="fileName">
      <div
        style="display: flex; justify-content: flex-start; align-items: center"
      >
        <img src="../../../../assets/exper/guide.png" class="chose-s2-icon" />
        <div class="chose-name">{{ fileName }}</div>
      </div>
      <img
        src="../../../../assets/globalIcon/dis-del.png"
        style="width: 13px; height: 14px; cursor: pointer"
        @click="clearFile"
      />
    </div>
    <!--<p style="color:#ff9900"> <Icon type="ios-information-circle-outline" />仅允许上传一个文件，如有多个文件需上传，请压缩后上传</p>-->
    <!--<p style="color:#ff9900"> <Icon type="ios-information-circle-outline" />请上传doc,pdf,jpg,png,zip,rar等格式文件</p>-->
    <!--，禁止上传*.exe|*.com|*.bat|*.vbs|等格式文件-->
    <p style="color: #ff0000" v-if="showTip">
      文件格式错误,请上传doc,pdf,jpg,png,zip,rar等格式文件
    </p>
	<!-- 文件大小不能超过20M -->
    <Table
      :show-header="false"
      :columns="fileCol"
      :data="fileList"
      v-show="fileList.length > 0"
    ></Table>
  </div>
</template>
<script>
	import {
		createCtfFiles,
		delCtfFiles,
		queryCtfFiles,
		delfile
	} from '@/api/question'
	import encryption from '@/libs/encryption.js'
	export default {
		props: ['show', 'curSaveFile', 'title'],
		data() {
			let September = sessionStorage.getItem('November')
			September = JSON.parse(encryption.SelfUseDecrypt(September))
			return {
				fileList: [],
				totalCount: 0,
				fileModal: {
					show: false,
					loading: true,
					title: '添加File'
				},
				formValidate: {
					chaId: this.chaId
				},
				fileCol: [
					//					{
					//						type: 'index',
					//						width: 60,
					//						align: 'center',
					//						ellipsis: true
					//					},
					{
						title: 'File',
						key: 'fileName',
						//						align: 'center',
						//						ellipsis: true,
						//						tooltip:true
					}, {
						title: '操作',
						width: 140,
						render: (h, params) => {
							return h('div', [
								h('Button', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										marginRight: '5px'
									}
								}, [
									h('a', {
										attrs: {
											href: "/api/minio/download/" + params.row.fileId,
											download: ''
										},
										style: {
											color: '#fff'
										}
									}, '下载')
								]),
								h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: '你确定要删除吗?',
										transfer: true
									},
									style: {
										marginLeft: '0px'
									},
									on: {
										'on-ok': () => {
											this.delCtfFiles(params.row.fileId)
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'error',
											size: 'small'
										},
										style: {
											marginRight: '5px'
										},
									}, '删除')
								])
							])
						}
					}
				],
				uploadAction: "/api/minio/upload/permanent",
				uploadHeader: {
					Authorization: localStorage.token,
					Accept: '*/*'
				},
				fileBucket: '',
				showTip: false,
				speed: 0,
				fileName: '',
				file: '',
				uploadList: []
			}
		},
		computed: {

		},
		filters: {

		},
		watch: {
			'show': function(show) {
				if(show) {
					this.showTip = false;
					//					this.queryCtfFiles();
				}
			},
			'curSaveFile': function(val) {
				this.file = val;
				if(this.file) {
					let info = val.info || {}
					this.fileName = info.originalName;
				}else{
					this.fileName = '';
				}
			}
		},
		methods: {
			delFile(id) {
				return new Promise((resolve, reject) => {
					delfile(id).then(data => {
						if(data.code == 1) {
							resolve()
						} else {
							this.$Message.error(data.message);
							reject()
						}
					}).catch(error => {
						console.log(error);
						this.$Message.error('删除文件失败');
					})
				})
			},
			delCtfFiles(id) {
				return new Promise((resolve, reject) => {
					delCtfFiles(id).then(data => {
						if(data.code == 1) {
							resolve();
						} else {
							this.$Message.warning(data.message);
							reject()
						}
					}).catch(error => {
						console.log(error);
						this.$Message.error('删除文件失败');
					})
				})
			},
			saveCtfFiles(file) {
				this.uploadList = [];
				if(file.code == 1) {
					this.file = file;
					this.fileName = file.info.originalName;
					this.$emit('setAttachmentFile', file)
				} else {
					this.file = '';
					this.fileName = '';
					this.$emit('setAttachmentFile', '')
					this.$Message.warning(file.message);
				}
			},
			clearFile() {
//				if(this.curSaveFile && this.file.info.id == this.curSaveFile.info.id) { //删除的是保存的文件
//					this.delCtfFiles(this.file.info.id).then(data => {
//						this.file = '';
//						this.fileName = '';
//						this.$emit('setAttachmentFile', '');
//					});
//				} else {
//					this.delFile(this.file.info.id).then(data => {
//						this.file = '';
//						this.fileName = '';
//						this.$emit('setAttachmentFile', '');
//					});
//				}
				this.file = '';
				this.fileName = '';
				let postFile = {
					info:{
						originalName:''
					},
					data:''
				}
				this.$emit('setAttachmentFile', postFile);
			},
			handleFormatError(sss) {
				this.showTip = true;
			},
			handleUploadSize() {
				this.showTip = true;
			},
			handleUpload(file) {
				this.uploadList = this.$refs.upload.fileList;
				// if((file.name || file.type).toLowerCase().indexOf("bat") != -1 || (file.name || file.type).toLowerCase().indexOf("exe") != -1 ||
				// 	(file.name || file.type).toLowerCase().indexOf("com") != -1 || (file.name || file.type).toLowerCase().indexOf("vbs") != -1 ||
				// 	(file.name || file.type).toLowerCase().indexOf("vbe") != -1 || (file.name || file.type).toLowerCase().indexOf("js") != -1 ||
				// 	(file.name || file.type).toLowerCase().indexOf("jse") != -1 || (file.name || file.type).toLowerCase().indexOf("wsh") != -1 ||
				// 	(file.name || file.type).toLowerCase().indexOf("wsf") != -1) {
				// 	this.showTip = true;
				// 	return false
				// }
				let exceededNum = file.name.lastIndexOf(".");
				let exceededStr = file.name.substring(exceededNum + 1, file.name.length).trim().toLowerCase();
				let type = exceededStr;
				let imageArr = ['jpg', 'jpeg', 'png'];
				let docArr = ['doc', 'docx', 'pdf'];
				let otherArr = ['zip', 'rar'];
				if(imageArr.includes(type)) {
					this.fileBucket = 'images';
					this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=images&bucket=images`
				} else if(docArr.includes(type)) {
					this.fileBucket = 'docs';
					this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs`
				} else if(otherArr.includes(type)) {
					this.fileBucket = 'files';
					this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=files&bucket=files`
				}else{
					this.showTip = true;
					return false
				}
				this.fileName = file.name;
				this.showTip = false;
				let promise = new Promise((resolve) => {
					this.$nextTick(function() {
						resolve(true)
					})
				});
				return promise
			},
			getFileSize(size) {
				let fileSize;
				if(size > 1024 * 1024) {
					fileSize = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
				} else {
					fileSize = (Math.round(size * 100 / 1024) / 100).toString() + 'KB'
				}
				return fileSize;
			},
			getProgress(progressEvent) {
				var aaspeed = Number(progressEvent.loaded - this.loaded) || 0
				this.loaded = progressEvent.loaded
				if(aaspeed > 1024 * 1024) {
					this.speed = (Math.round(aaspeed * 100 / (1024 * 1024)) / 100).toString() + 'MB/s'
				} else {
					this.speed = (Math.round(aaspeed * 100 / 1024) / 100).toString() + 'KB/s'
				}
			},
		},
		mounted() {
			if(this.curSaveFile) {
				let info = this.curSaveFile.info || {}
				this.fileName = info.originalName;
				this.file = JSON.parse(JSON.stringify(this.curSaveFile));
			}
		},
		created() {

		}
	}
</script>
<style scoped>
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
</style>
<style>
.chose-wrap {
  display: flex;
  justify-content: space-between;
  padding: 3px 8px;
  background-color: var(--table-tr-hover-color);
  align-items: center;
  margin-top: 10px;
}

.chose-name {
  width: 300px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chose-s-icon {
  width: 15px;
  height: 17px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}

.chose-s2-icon {
  width: 13px;
  height: 15px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}
</style>